<?php

namespace Admin\Controller;
use Common\Controller\BackendController;
class ShopController extends BackendController {
	public function _initialize() {
        parent::_initialize();
        $this->_mod = D('TejiaCate');
		$api_config = M('ItemsSite')->where(array('code' => 'itaoke'))->getField('config');
        $this->_itkconfig = unserialize($api_config);
    }

	public function index(){
		$this->display();
	}

	public function setting(){
		if(IS_POST){
			$cate_id	= I('cate_id', 'trim');
			$url		= I('url', 'trim');
			$q			= I('q');
			$q			= urlencode($q);
			$sprice		= I('sprice', 'trim');
			$eprice		= I('eprice', 'trim');
			$sort		= I('sort', 'trim');
			$page		= I('page', 'trim');
			$coupon_start_time	= strtotime($_POST['coupon_start_time']);
			$coupon_end_time	= strtotime($_POST['coupon_end_time']);
			$url		= str_replace('http:','https:',$url);
			if(!$url){
				$this->ajaxReturn(0, '店铺地址必须填写！');
			}
			if(!$cate_id){
				$this->ajaxReturn(0, '入库分类必须选择!');
			}
			F('shop_setting', array(
				'cate_id' => $cate_id, 
				'q' => $q, 
				'url' =>$url, 
				'sprice' =>$sprice, 
				'eprice' =>$eprice, 
				'page' => $page, 
				'sort' => $sort, 
				'coupon_start_time' => $coupon_start_time, 
				'coupon_end_time' => $coupon_end_time, 
			));
			$this->collect();
		}
	}
	public function collect(){
        set_time_limit(0);
        if (false === ($_var_7 = F('shop_setting'))) {
            $this->ajaxReturn(0, L('illegal_parameters'));
        }
        $_var_8 = $this->_get('p', 'intval', 1);

        $_var_9 = $_var_7['page'];
        if ($_var_8 > 1) {
            if ($_var_8 > $_var_9) {
                $this->ajaxReturn(0, '已经采集完成' . $_var_9 . '页！请返回 ！');
            }
        }
        if ($_var_8 == 1) {
            $_var_10 = 0;
        } else {
            $_var_10 = F('totalcoll');
        }
        
        // 调用itaoke接口进行数据采集
        $ApiParas['itemurl'] = $_var_7['url'];
        $ApiParas['q'] = $_var_7['q'];
        $ApiParas['p'] = $_var_8;
        $tb_top = $this->_get_top();
        $req = $tb_top->load_api('ItaokeShopGetRequest');
        $req->setFields( $ApiParas );
        
        $resp = (array)$tb_top->execute($req);
        if($resp['status'] != '0000')
        {
        	$this->ajaxReturn(0, $resp['msg']);
        }
        else
        {
        	// 采集itaoke开放平台返回的数据
        }
        
        $_var_11 = 0;
        $_var_12 = stripslashes(base64_decode($resp['data']));
        $_var_12 = iconv('GBK', 'UTF-8//IGNORE', $_var_12);
        $_var_12 = rtrim(ltrim(trim($_var_12), '("'), '")');
        if (strpos($_var_12, '<p class="item-not-found"><strong>没找到符合条件的商品,换个条件或关键词试试吧。</strong></p>')) {
            $this->ajaxReturn(0, '没找到符合条件的商品,换个条件或关键词试试吧。');
        }
        if (preg_match_all('/<dl class="item(.*?)<\\/dl>/s', $_var_12, $_var_13)) {
            for ($_var_14 = 0; $_var_14 < count($_var_13[1]); $_var_14++) {
                $_var_15 = $_var_13[1][$_var_14];
                $_var_16 = get_word($_var_15, 'data-id="', '">');
                $_var_17 = rand(99, 9999);
                $_var_18 = '1';
                $_var_19 = 'http://hws.m.taobao.com/cache/wdetail/5.0/?id=' . $_var_16;
                $_var_20 = curl_init();
                curl_setopt($_var_20, CURLOPT_URL, $_var_19);
                curl_setopt($_var_20, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($_var_20, CURLOPT_FOLLOWLOCATION, true);
                curl_setopt($_var_20, CURLOPT_MAXREDIRS, 2);
                $_var_21 = curl_exec($_var_20);
                curl_close($_var_20);
                $_var_22 = json_decode($_var_21, true);
                $_var_23 = array();
                $_var_24 = json_decode($_var_22['data']['apiStack'][0]['value'], true);
                $_var_23['title'] = $_var_22['data']['itemInfoModel']['title'];
                $_var_23['volume'] = $_var_24['data']['itemInfoModel']['totalSoldQuantity'];
                $_var_23['coupon_price'] = $_var_24['data']['itemInfoModel']['priceUnits'][0]['price'];
                if (substr_count($_var_23['coupon_price'], '-')) {
                    $_var_25 = explode('-', $_var_23['coupon_price']);
                    $_var_23['coupon_price'] = min($_var_25[0], $_var_25[1]);
                }
                $_var_23['price'] = $_var_24['data']['itemInfoModel']['priceUnits'][1]['price'];
                if (substr_count($_var_23['price'], '-')) {
                    $_var_24 = explode('-', $_var_23['price']);
                    $_var_23['price'] = min($_var_24[0], $_var_24[1]);
                }
                $_var_23['pic_url'] = $_var_22['data']['itemInfoModel']['picsPath'][0];
                $_var_23['pic_url'] = str_replace('_320x320.jpg', '', $_var_23['pic_url']);
                $_var_23['sellerId'] = $_var_22['data']['seller']['userNumId'];
                $_var_23['nick'] = $_var_22['data']['seller']['nick'];
                $_var_23['type'] = $_var_22['data']['seller']['type'];
                $_var_26 = $_var_23['type'];
                $_var_27 = $_var_23['pic_url'];
                $_var_28 = $_var_23['volume'];
                $_var_29 = $_var_23['coupon_price'];
                $_var_30 = $_var_23['price'];
                $_var_31 = round($_var_29 / $_var_30 * 10, 1);
                $_var_32 = $_var_23['title'];
                $_var_33 = D('Items')->get_tags_by_title($_var_32);
                $_var_34 = implode(',', $_var_33);
                $_var_35['shop_type'] = $_var_26;
                $_var_35['title'] = $_var_32;
                $_var_35['tags'] = $_var_34;
                $_var_35['intro'] = '原价：' . $_var_30 . '元，折扣后价格：' . $_var_29 . '元，' . $_var_17 . '人觉得不错，目前已有' . $_var_28 . '人参与抢购。';
                $_var_35['pic_url'] = $_var_27;
                $_var_35['num_iid'] = $_var_16;
                $_var_35['price'] = $_var_30;
                $_var_35['coupon_price'] = $_var_29;
                $_var_35['volume'] = $_var_28 + 1;
                $_var_35['nick'] = $_var_23['nick'];
                $_var_35['sellerId'] = $_var_23['sellerId'];
                $_var_35['ems'] = $_var_18;
                $_var_35['likes'] = $_var_17;
                $_var_35['cate_id'] = $_var_7['cate_id'];
                $_var_35['sex'] = $_var_7['sex'];
                $_var_35['coupon_rate'] = $_var_36 * 10000;
                $_var_35['coupon_end_time'] = $_var_7['coupon_end_time'];
                $_var_35['coupon_start_time'] = $_var_7['coupon_start_time'];
                $_var_35['astime'] = date('Ymd');
                
                if ($_var_32 && $_var_27 && $_var_16) {
                    $_var_37['item_list'][] = $_var_35;
                }
            }
        }
        foreach ($_var_37['item_list'] as $_var_38 => $_var_39) {
            $_var_40 = $this->_ajax_tb_publish_insert($_var_39);
            if ($_var_40 > 0) {
                $_var_11++;
            }
            $_var_10++;
        }
        if (strpos($_var_12, '<a class="disable">下一页</a>')) {
            $this->ajaxReturn(0, '已经采集完成' . $_var_8 . '页,本次采集到' . $_var_10 . '件商品！请返回，爱淘客提供采集技术支持');
        }
        F('totalcoll', $_var_10);
        $this->assign('p', $_var_8);
        $this->assign('coll', $_var_11);
        $this->assign('totalnum', $_var_41);
        $this->assign('totalcoll', $_var_10);
        $_var_42 = $this->fetch('collect');
        $this->ajaxReturn(1, '', $_var_42);
	}
	 

	private function _ajax_tb_publish_insert($item) {
        $item['title'] = strip_tags($item['title']);
        $result = D('Items')->ajax_yg_publish($item);
        return $result;
    }

	private function _get_top() {
        vendor('Itaoke.TopClient');
        vendor('Itaoke.RequestCheckUtil');
        vendor('Itaoke.Logger');
        $top = new \TopClient;
        $top->appkey = $this->_itkconfig['app_key'];
        $top->secretKey = $this->_itkconfig['app_secret'];
        return $top;
    }

}